package com.youlai.core.mybatisplus.handler;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 全局设置字段策略为not_null, 要把null的字段也更新到数据库，需要用下面的类，使用方式：
 * userService.update(WrappersFactory.updateWithNullField(user).eq(User::getId,"0001"));
 */
public class WrappersFactory {

    private final static List<String> ignoreList = new ArrayList<>();

    static {
        ignoreList.add("id");
        ignoreList.add("deleted");
        ignoreList.add("status");
        ignoreList.add("updateTime");
        ignoreList.add("updateBy");
        ignoreList.add("createTime");
        ignoreList.add("createBy");
    }

    public static <T> LambdaUpdateWrapper<T> updateWithNullField(T entity) {
        UpdateWrapper<T> updateWrapper = new UpdateWrapper<>();
        List<Field> allFields = TableInfoHelper.getAllFields(entity.getClass());
        MetaObject metaObject = SystemMetaObject.forObject(entity);
        for (Field field : allFields) {
            Object value = metaObject.getValue(field.getName());
            if (ignoreList.contains(field.getName()) && value==null) {

            }else {
                updateWrapper.set(StringUtils.camelToUnderline(field.getName()), value);
            }
        }
        return updateWrapper.lambda();
    }

}
